package com.ibeetl.cms.web;

import com.ibeetl.admin.console.service.UserConsoleService;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.entity.CoreUserRole;
import com.ibeetl.admin.core.file.FileService;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.util.AESUtil;
import com.ibeetl.admin.core.util.ConvertUtil;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.util.enums.GeneralStateEnum;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.cms.entity.Enterprise;
import com.ibeetl.cms.entity.EssentialInformation;
import com.ibeetl.cms.entity.UserBasicInformation;
import com.ibeetl.cms.service.EnterpriseService;
import com.ibeetl.cms.service.EssentialInformationService;
import com.ibeetl.cms.util.RoleConstant;
import com.ibeetl.cms.web.query.EmployeeManageQuery;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;
import java.util.List;

/**
 * @author likai
 * @date 2018/10/23
 */

@Controller
public class EmployeeManageController {

    private final Log log = LogFactory.getLog(this.getClass());
    private static final String MODEL = "/cms/employeeManager";

    @Autowired
    CorePlatformService platformService;

    @Autowired
    UserConsoleService userConsoleService;

    @Autowired EnterpriseService enterpriseService;

    @Autowired
    FileService fileService;

    @Autowired
    private EssentialInformationService essentialInformationService;
    /* 页面 */

    @GetMapping(MODEL + "/index.do")
    @Function("employeeManage")
    @ResponseBody
    public ModelAndView index() {
        ModelAndView view = new ModelAndView("/cms/employeeManage/index.html") ;
        view.addObject("search", EmployeeManageQuery.class.getName());
        return view;
    }

    @GetMapping(MODEL + "/edit.do")
    @Function("employeeManage")
    @ResponseBody
    public ModelAndView edit(Integer id) {
        ModelAndView view = new ModelAndView("/cms/employeeManage/edit.html");
        CoreUser user = userConsoleService.queryById(id);
        view.addObject("user", user);
        return view;
    }

    @GetMapping(MODEL + "/add.do")
    @Function("employeeManage")
    @ResponseBody
    public ModelAndView add() {
        CoreUser currentUser = platformService.getCurrentUser();
        ModelAndView view = new ModelAndView("/cms/employeeManage/add.html");
        view.addObject("companyName", enterpriseService.findCompanyId(currentUser.getId()).getEnterpriseName());
        return view;
    }

    /* ajax json */

    @PostMapping(MODEL + "/list.json")
    @Function("employeeManage")
    @ResponseBody
    public JsonResult<PageQuery<CoreUser>> list(EmployeeManageQuery condtion)
    {
        CoreUser companyUser = platformService.getCurrentUser();

        PageQuery<CoreUser> page = condtion.getPageQuery();
        condtion.setRoleId(RoleConstant.PERSON);
        condtion.setCompanyId(companyUser.getId());
        userConsoleService.getUserAndRole(page);
        return JsonResult.success(page);
    }

    @PostMapping(MODEL + "/delete.json")
    @Function("employeeManage")
    @ResponseBody
    public JsonResult delete(String ids) {
        List<Long> dels = ConvertUtil.str2longs(ids);
        userConsoleService.batchDelSysUser(dels);
        return JsonResult.success();
    }

    @PostMapping(MODEL + "/update.json")
    @Function("employeeManage")
    @ResponseBody
    public JsonResult update(@Validated(ValidateConfig.UPDATE.class) CoreUser user) {
        user.setCode(user.getCardNumber());
        boolean success = userConsoleService.updateTemplate(user);
        if (success) {
            this.platformService.clearFunctionCache();
            return JsonResult.success();
        } else {
            return JsonResult.failMessage("保存失败！");
        }
    }

    @PostMapping(MODEL + "/add.json")
    @Function(value="employeeManage",name="企业添加人才")
    @ResponseBody
    public JsonResult<Long> add(@Validated(ValidateConfig.ADD.class) CoreUser user) {
        if (!platformService.isAllowUserName(user.getCode())) {
            return JsonResult.failMessage("不允许的注册名字 " + user.getCode());
        }
        List<CoreUser> userList = userConsoleService.queryUserByCode(user.getCode());
        if(null != userList && userList.size() > 0){
            return JsonResult.failMessage("用户已存在" + user.getCode());
        }
        CoreUser companyUser = platformService.getCurrentUser();

        user.setCreateTime(new Date());
        user.setPassword("abc123");
        user.setCompanyId(companyUser.getId());
        user.setRoleId(RoleConstant.PERSON);
        user.setOrgId((long) 1);
        user.setNeedInfo("1");
        userConsoleService.saveUser(user);

        CoreUserRole coreUserRole = new CoreUserRole();
        coreUserRole.setUserId(user.getId());
        coreUserRole.setRoleId(RoleConstant.PERSON);
        coreUserRole.setOrgId((long) 1);
        userConsoleService.saveUserRole(coreUserRole);

        /**
         * 在个人基本信息中插入一条记录
         */
        EssentialInformation essentialInformation = new EssentialInformation();
        essentialInformation.setUserId(Math.toIntExact(user.getId()));
        essentialInformation.setName(user.getName());
        essentialInformation.setIdType(user.getCardType());
        essentialInformation.setIdentificationNumber(user.getCardNumber());

        essentialInformation.setCompanyId(Math.toIntExact(companyUser.getId()));
        essentialInformation.setCurrentWorkingEnterprise(companyUser.getName());
        essentialInformationService.save(essentialInformation);
        return JsonResult.success(user.getId());
    }

    @PostMapping(MODEL + "/view.json")
    @ResponseBody
    @Function("employeeManage")
    public JsonResult<CoreUser> view(Long id) {
        CoreUser user = userConsoleService.queryById(id);
        return JsonResult.success(user);
    }




    @PostMapping(MODEL + "/disable.json")
    @Function("employeeManage")
    @ResponseBody
    public JsonResult disableUser(String ids) {

        List<Long> dels = ConvertUtil.str2longs(ids);

        userConsoleService.batchUpdateUserState(dels, GeneralStateEnum.DISABLE);
        for (Long id : dels) {
            CoreUser user = userConsoleService.queryById(id);
            this.platformService.restUserSession(user.getCode());
        }
        return JsonResult.success();

    }

    /**
     * 启用用户操作
     *
     * @return
     */
    @PostMapping(MODEL + "/enable.json")
    @Function("employeeManage")
    @ResponseBody
    public JsonResult enableUser(String ids) {

        List<Long> enables = ConvertUtil.str2longs(ids);
        userConsoleService.batchUpdateUserState(enables, GeneralStateEnum.ENABLE);
        return JsonResult.success();

    }

    /**
     * 管理员重置用户密码
     *
     * @return
     */
    @PostMapping(MODEL + "/changePassword.json")
    @Function("employeeManage")
    @ResponseBody
    public JsonResult changePassword(Long id, String password) {

        userConsoleService.resetPassword(id, password);
        return JsonResult.success();
    }
    //修改密码
    @GetMapping(MODEL + "/changePassword.do")
    public ModelAndView changePassword(Long id) {
        CoreUser user = userConsoleService.queryById(id);
        ModelAndView view = new ModelAndView("/admin/user/changePassword.html");
        view.addObject("user", user);
        return view;
    }





    /**
     * 企业开户
     * @return
     */
    @GetMapping(MODEL + "/examineIndex.do")
    @Function("employeeManage.query")
    @ResponseBody
    public ModelAndView examineIndex() {
        ModelAndView view = new ModelAndView("/cms/employeeManage/examineIndex.html") ;
        view.addObject("search", EmployeeManageQuery.class.getName());
        return view;
    }

    @GetMapping(MODEL + "/examineEdit.do")
    @Function("employeeManage.query")
    @ResponseBody
    public ModelAndView examineEdit(Integer id) {
        ModelAndView view = new ModelAndView("/cms/employeeManage/examineEdit.html");
        CoreUser user = userConsoleService.queryById(id);
        view.addObject("user", user);
        Enterprise enterprise=enterpriseService.queryByUserId(id);
        view.addObject("enterprise", enterprise);
        return view;
    }

    @GetMapping(MODEL + "/examineAdd.do")
    @Function("employeeManage.query")
    @ResponseBody
    public ModelAndView examineAdd() {
        ModelAndView view = new ModelAndView("/cms/employeeManage/examineAdd.html");
        List<Enterprise> org=enterpriseService.findEnterpriseInfo();//查询所有企业基本信息的组织机构和企业名
        view.addObject("org",org);
        view.addObject("passWord",String.valueOf((int)((Math.random()*9+1)*100000)));
        return view;
    }

    /* ajax json */

    @PostMapping(MODEL + "/examineList.json")
    @Function("employeeManage.query")
    @ResponseBody
    public JsonResult<PageQuery<CoreUser>> examineList(EmployeeManageQuery condtion)
    {
        PageQuery<CoreUser> page = condtion.getPageQuery();
        condtion.setRoleId(RoleConstant.COMPANY);
        userConsoleService.getUserAndRole(page);
        return JsonResult.success(page);
    }

    @PostMapping(MODEL + "/examineDelete.json")
    @Function("employeeManage.query")
    @ResponseBody
    public JsonResult examineDelete(String ids) {
        List<Long> dels = ConvertUtil.str2longs(ids);
        userConsoleService.deleteSysUser(dels);
        enterpriseService.deleteEnterprise(dels);//删除企业用户后，同时删除对应的企业基本信息
        return JsonResult.success();
    }

    @PostMapping(MODEL + "/examineUpdate.json")
    @Function("employeeManage.query")
    @ResponseBody
    public JsonResult examineUpdate(@Validated(ValidateConfig.UPDATE.class) UserBasicInformation userBasicInformation) {
        CoreUser user=new CoreUser();
        user.setId((long)userBasicInformation.getId());
        user.setCode(userBasicInformation.getCode());
        user.setName(userBasicInformation.getName());
        boolean success = userConsoleService.updateTemplate(user);//修改账户信息

        Enterprise enterprise=new Enterprise();
        enterprise.setId(enterpriseService.queryByUserId(userBasicInformation.getId()).getId());
        enterprise.setEnterpriseLegalPerson(userBasicInformation.getEnterpriseLegalPerson());
        enterprise.setEphoneNumber(userBasicInformation.getEphoneNumber());
        enterprise.setEnterpriseTelephone(userBasicInformation.getEnterpriseTelephone());
        enterprise.setMail(userBasicInformation.getMail());
        enterprise.setEnterpriseName(userBasicInformation.getName());
        enterpriseService.updateTemplate(enterprise);


        if (success) {
            this.platformService.clearFunctionCache();
            return JsonResult.success();
        } else {
            return JsonResult.failMessage("保存失败！");
        }
    }

    @PostMapping(MODEL + "/examineAdd.json")
    @Function("employeeManage.query")
    @ResponseBody
    public JsonResult<Long> examineAdd(@Validated(ValidateConfig.ADD.class) UserBasicInformation userBasicInformation) {
        if (!platformService.isAllowUserName(userBasicInformation.getCode())) {
            return JsonResult.failMessage("不允许的注册名字 " + userBasicInformation.getCode());
        }
        CoreUser user=new CoreUser();
        user.setOrganizationCode(userBasicInformation.getOrganizationCode());
        user.setCode(userBasicInformation.getCode());
        user.setName(userBasicInformation.getName());
        user.setOrgId((long)1);
        user.setCreateTime(new Date());
        user.setPassword(userBasicInformation.getPassWord());
        user.setRoleId(RoleConstant.COMPANY);
        user.setNeedInfo("1");
        userConsoleService.saveUser(user);

        CoreUserRole coreUserRole = new CoreUserRole();
        coreUserRole.setUserId(user.getId());
        coreUserRole.setOrgId((long)1);
        coreUserRole.setRoleId(RoleConstant.COMPANY);
        coreUserRole.setCreateTime(new Date());
        userConsoleService.saveUserRole(coreUserRole);

        /**
         * 修改企业基本信息中修改user_id
         */
        Enterprise enterprise = new Enterprise();
        enterprise.setUserId(user.getId().intValue());
        enterprise.setEnterpriseName(userBasicInformation.getName());
        enterprise.setOrganizationCode(userBasicInformation.getOrganizationCode());
        enterprise.setEnterpriseLegalPerson(userBasicInformation.getEnterpriseLegalPerson());
        enterprise.setEnterpriseDirectory(userBasicInformation.getEnterpriseDirectory());
        enterprise.setDirectoryEnterprises(userBasicInformation.getDirectoryEnterprises());
        enterprise.setBusinessQuota(userBasicInformation.getBusinessQuota());
        enterpriseService.save(enterprise);
        return JsonResult.success(user.getId());
    }

    @PostMapping(MODEL + "/examineView.json")
    @ResponseBody
    @Function("employeeManage.query")
    public JsonResult<CoreUser> examineView(Long id) {
        CoreUser user = userConsoleService.queryById(id);
        return JsonResult.success(user);
    }

    @PostMapping(MODEL + "/examineDisable.json")
    @Function("employeeManage.query")
    @ResponseBody
    public JsonResult examineDisable(String ids) {

        List<Long> dels = ConvertUtil.str2longs(ids);

        userConsoleService.batchUpdateUserState(dels, GeneralStateEnum.DISABLE);
        for (Long id : dels) {
            CoreUser user = userConsoleService.queryById(id);
            this.platformService.restUserSession(user.getCode());
        }
        return JsonResult.success();

    }

    /**
     * 启用用户操作
     *
     * @return
     */
    @PostMapping(MODEL + "/examineEnable.json")
    @Function("employeeManage.query")
    @ResponseBody
    public JsonResult examineEnable(String ids) {

        List<Long> enables = ConvertUtil.str2longs(ids);
        userConsoleService.batchUpdateUserState(enables, GeneralStateEnum.ENABLE);
        return JsonResult.success();

    }

    /**
     * 管理员重置用户密码
     *
     * @return
     */
    @PostMapping(MODEL + "/examineChangePassword.json")
    @Function("employeeManage.query")
    @ResponseBody
    public JsonResult examineChangePassword(Long id, String password) {

        userConsoleService.resetPassword(id, password);
        return JsonResult.success();
    }

    //修改密码
    @GetMapping(MODEL + "/examineChangePassword.do")
    @Function("employeeManage.query")
    public ModelAndView examineChangechangePassword(Long id) {
        CoreUser user = userConsoleService.queryById(id);
        ModelAndView view = new ModelAndView("/cms/employeeManage/examineChangePassword.html");
        view.addObject("user", user);
        return view;
    }

    @GetMapping(MODEL + "/getCodeAndPassword.json")
    @Function("employeeManage.query,employeeManage")
    @ResponseBody
    public JsonResult<CoreUser> getOrgCodeAndPassword(Long id) {
        CoreUser user = userConsoleService.queryById(id);
        user.setPassword(AESUtil.decrypt(user.getPassword(),AESUtil.PWD));
        return JsonResult.success(user);
    }
}
